using Identity.Application.Contracts.Common;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Application.Permissions.Commands;
using Identity.Application.Permissions.Interfaces;
using MediatR;

namespace Identity.Application.Permissions.CommandHandlers;

public class ChangePermissionDescriptionCommandHandler : IRequestHandler<ChangePermissionDescriptionCommand, Result>
{
    private readonly IPermissionsRepository _permissionsRepository;
    private readonly IApiPermissionBindingReadService _apiPermissionBindingReadService;
    private readonly IUnitOfWork _unitOfWork;
    public ChangePermissionDescriptionCommandHandler(IPermissionsRepository permissionsRepository,IApiPermissionBindingReadService apiPermissionBindingReadService, IUnitOfWork unitOfWork)
    {
        _permissionsRepository = permissionsRepository;
        _apiPermissionBindingReadService = apiPermissionBindingReadService;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result> Handle(ChangePermissionDescriptionCommand request, CancellationToken cancellationToken)
    {
        var permission = await _permissionsRepository.GetPermissionByIdAsync(request.Id);
        if (permission == null) return Result.Failure("权限不存在");

        permission.ChangeDescription(request.description);

        await _unitOfWork.SaveChangesAsync(cancellationToken);
        
        var apipermission = await _apiPermissionBindingReadService.GetBindingsByPermissionKeyAsync(permission.Key);
        var serviceName = apipermission.ToList().FirstOrDefault()?.fromServiceName;
        return Result.Success(new PermissionDto(permission.Id, permission.Name,permission.Key, permission.Description,serviceName,!string.IsNullOrWhiteSpace(serviceName)));
    }
}